package com.mall.search.mallsearch.service.impl;

import com.mall.search.mallsearch.service.IOperationFacade;
import com.mall.search.mallsearch.util.CodeHelperUtil;
import com.mall.search.mallsearch.util.ExcelUtils;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.math.BigDecimal;
import java.net.URL;
import java.net.URLConnection;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;


@Service
public class OperationFacadeImpl implements IOperationFacade {

    private static final Logger logger = LoggerFactory.getLogger(OperationFacadeImpl.class);


    @Override
    public String addCenterPointFromExcel(InputStream is) throws Exception  {
        XSSFWorkbook wb = ExcelUtils.openXSSFWorkbook(is);
        Sheet sheet = wb.getSheetAt(0);
        // 总行数
        String sheetName = sheet.getSheetName();
        String path = "/Users/hehan/Desktop/es/data/"+sheetName;
        File dir = new File(path);
        if(!dir.exists()){
            dir.mkdirs();
        }
        int trLength = sheet.getLastRowNum();
        logger.info("add centerPoint from excel ,trLength is {}", trLength);
        for (int i = 1; i <= trLength; i++) {
            Row row = sheet.getRow(i);
            try {
                row.getCell(0).setCellType(Cell.CELL_TYPE_STRING);
                String modelIdMsg = row.getCell(0).getStringCellValue();
                int modelId = Integer.parseInt(modelIdMsg);
                row.getCell(1).setCellType(Cell.CELL_TYPE_STRING);
                String file_num = row.getCell(1).getStringCellValue();
                row.getCell(2).setCellType(Cell.CELL_TYPE_STRING);
                String urlstring = row.getCell(2).getStringCellValue();
                String name = String.valueOf(modelId) + "_" + file_num + ".mx";
                URL url = new URL(urlstring);
                int bytesum = 0;
                int byteread = 0;
                URLConnection conn = url.openConnection();
                InputStream inStream = conn.getInputStream();
                FileOutputStream fs = null;

                    String pathName = Paths.get(path, name).toString();
                    fs = new FileOutputStream(pathName);

                    byte[] buffer = new byte[1024];
                    while ((byteread = inStream.read(buffer)) != -1) {
                        bytesum += byteread;
                        fs.write(buffer, 0, byteread);
                    }

                } catch (Exception e) {
                    System.out.println(e);
                }
            }



        return null;
    }
}
